const fs = require('fs-extra')
const R = require('ramda')
const {booksFile} = require('./config')
const print = require('./lib/print')

const search = async (options) => {
  const booksInFile = await fs.readJson(booksFile)
  const whereObj = R.pipe(
    R.pick(['author', 'title', 'tags']),
    R.filter(R.complement(R.isNil)),
    R.map(R.contains)
  )(options)
  const order = R.defaultTo('descend', options.order)
  const sortField = R.defaultTo('price', options.sort)
  R.pipe(
    R.filter(R.where(whereObj)),
    R.sort(R[order](R.prop(sortField))),
    R.map(print)
  )(booksInFile)
}

module.exports = search
